package com.yangzb.spring.batch.service;

import cn.hutool.core.convert.Convert;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.ItemWriteListener;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class MItemWriteListener implements ItemWriteListener<Map> {
    private DataSource ds;
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public MItemWriteListener(DataSource ds) {
        this.ds = ds;
        if (namedParameterJdbcTemplate == null) {
            this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(ds);
        }
    }

    @Override
    public void beforeWrite(List<? extends Map> items) {


    }

    private String sql() {
        StringBuffer sql = new StringBuffer("delete from contact_order_1100_3 where CONTACT_ORDER_ID in (:ids)");
        return sql.toString();
    }

    @Override
    public void afterWrite(List<? extends Map> items) {
        String sql = sql();
        Map<String, Object> params = new HashMap<>();
        List<Object> contact_order_id = items.stream().map(map -> map.get("CONTACT_ORDER_ID")).collect(Collectors.toList());
        params.put("ids", contact_order_id);
        int update = 0;
        try {
            update = namedParameterJdbcTemplate.update(sql, params);
        } catch (Exception e) {
            log.error("", e);
            throw new RuntimeException(e);
        }
        if (update != items.size()+1) {
            throw new RuntimeException("删除失败，update：" + update);
        }
    }

    @Override
    public void onWriteError(Exception exception, List<? extends Map> items) {

    }
}
